package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en_AE"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"mxshop-api/global"
	"reflect"
	"strings"
)

// InitTrans 初始化翻译器
func InitTrans(local string) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		//注册一个获取json的tag的自定义方法(错误提示的时候让他用json的字段提示)
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})

		zhT := zh.New()    //中文翻译器
		enT := en_AE.New() //英文翻译器
		//第一个参数是备用的语言环境(相当于默认值),第二个后面的参数是应该支持的语言环境
		uni := ut.New(enT, zhT, enT)
		var ok bool
		//这个地方注意不能是:= 会变成局部变量了   = 不会变成局部变量
		global.Trans, ok = uni.GetTranslator(local)
		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s) faild", local)
		}
		//注册翻译器
		switch local {
		case "en":
			err = enTranslations.RegisterDefaultTranslations(v, global.Trans)
		case "zh":
			err = zhTranslations.RegisterDefaultTranslations(v, global.Trans)
		default:
			err = enTranslations.RegisterDefaultTranslations(v, global.Trans)
		}
		return err
	}
	return nil
}
